package com.dg.river.core.util;

import static com.lzy.okgo.model.Progress.FILE_NAME;

import android.content.Context;
import android.content.SharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by hy on 2018/10/16
 * Description : SharedPreferences工具类
 */
public class SPUtils {

    private static String DEFAULT_FILE_NAME = "shareData";

    public static SharedPreferences getInstance(Context mContext) {
        if (mContext != null) {
            return mContext.getSharedPreferences(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
        } else {
            return null;
        }
    }

    public static SharedPreferences.Editor getInstanceEdit(Context mContext) {
        if (mContext != null) {
            return getInstance(mContext).edit();
        } else {
            return null;
        }
    }

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param context
     * @param file_name 文件名称
     * @param key
     * @param object
     */
    public static void put(Context context, String file_name, String key, Object object) {
        if (object != null && context != null) {
            SharedPreferences sp;
            if (file_name != null) {
                sp = context.getSharedPreferences(file_name, Context.MODE_PRIVATE);
            } else {
                sp = context.getSharedPreferences(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
            }
            SharedPreferences.Editor editor = sp.edit();
            if (object instanceof String) {
                editor.putString(key, (String) object);
            } else if (object instanceof Integer) {
                editor.putInt(key, (Integer) object);
            } else if (object instanceof Boolean) {
                editor.putBoolean(key, (Boolean) object);
            } else if (object instanceof Float) {
                editor.putFloat(key, (Float) object);
            } else if (object instanceof Long) {
                editor.putLong(key, (Long) object);
            } else {
                editor.putString(key, object.toString());
            }
            SharedPreferencesCompat.apply(editor);
        }
    }

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     */
    public static void put(Context context, String key, Object object) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            if (object == null) {
                editor.putString(key, "");
            } else {
                editor.putString(key, object.toString());
            }
        }

        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param context
     * @param file_name 文件名称
     */
    public static void putMap(Context context, String file_name, Map<String, Object> map) {
        SharedPreferences sp;
        if (file_name != null) {
            sp = context.getSharedPreferences(file_name, Context.MODE_PRIVATE);
        } else {
            sp = context.getSharedPreferences(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor editor = sp.edit();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof String) {
                editor.putString(entry.getKey(), (String) entry.getValue());
            } else if (entry.getValue() instanceof Integer) {
                editor.putInt(entry.getKey(), (Integer) entry.getValue());
            } else if (entry.getValue() instanceof Boolean) {
                editor.putBoolean(entry.getKey(), (Boolean) entry.getValue());
            } else if (entry.getValue() instanceof Float) {
                editor.putFloat(entry.getKey(), (Float) entry.getValue());
            } else if (entry.getValue() instanceof Long) {
                editor.putLong(entry.getKey(), (Long) entry.getValue());
            } else {
                editor.putString(entry.getKey(), entry.getValue().toString());
            }
        }
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 存储List数据
     *
     * @param mContext
     * @param key
     * @param data
     */
    public static void putList(Context mContext, String file_name, String key, List<Map<String, String>> data) {
        JSONArray mJsonArray = new JSONArray();
        for (int i = 0; i < data.size(); i++) {
            Map<String, String> itemMap = data.get(i);
            Iterator<Map.Entry<String, String>> iterator = itemMap.entrySet().iterator();
            JSONObject object = new JSONObject();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                try {
                    object.put(entry.getKey(), entry.getValue());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            mJsonArray.put(object);
        }
        SPUtils.put(mContext, file_name, key, mJsonArray.toString());
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     */
    public static Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_MULTI_PROCESS);

        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param mContext
     * @param file_name     文件名称
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(Context mContext, String file_name, String key, Object defaultObject) {
        if (mContext != null) {
            SharedPreferences sp;
            if (file_name != null) {
                sp = mContext.getSharedPreferences(file_name, Context.MODE_PRIVATE);
            } else {
                sp = mContext.getSharedPreferences(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
            }
            if (defaultObject instanceof String) {
                return sp.getString(key, (String) defaultObject);
            } else if (defaultObject instanceof Integer) {
                return sp.getInt(key, (Integer) defaultObject);
            } else if (defaultObject instanceof Boolean) {
                return sp.getBoolean(key, (Boolean) defaultObject);
            } else if (defaultObject instanceof Float) {
                return sp.getFloat(key, (Float) defaultObject);
            } else if (defaultObject instanceof Long) {
                return sp.getLong(key, (Long) defaultObject);
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * 获取List数据
     *
     * @param mContext
     * @param key
     * @return
     */
    public static List<Map<String, String>> getList(Context mContext, String file_name, String key) {
        List<Map<String, String>> datas = new ArrayList<>();
        SharedPreferences sp = mContext.getSharedPreferences(file_name, Context.MODE_PRIVATE);
        String result = sp.getString(key, "");
        try {
            JSONArray array = new JSONArray(result);
            for (int i = 0; i < array.length(); i++) {
                JSONObject itemObject = array.getJSONObject(i);
                Map<String, String> itemMap = new HashMap<>();
                JSONArray names = itemObject.names();
                if (names != null) {
                    for (int j = 0; j < names.length(); j++) {
                        String name = names.getString(j);
                        String value = itemObject.getString(name);
                        itemMap.put(name, value);
                    }
                }
                datas.add(itemMap);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return datas;
    }


    /**
     * 移除某个key值以及对应的值
     *
     * @param context
     * @param file_name 文件名称
     * @param key
     */
    public static void remove(Context context, String file_name, String key) {
        SharedPreferences sp;
        if (file_name != null) {
            sp = context.getSharedPreferences(file_name, Context.MODE_PRIVATE);
        } else {
            sp = context.getSharedPreferences(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }


    /**
     * 清除所有数据
     *
     * @param context
     */
    public static void clear(Context context, String file_name) {
        SharedPreferences sp;
        if (file_name != null) {
            sp = context.getSharedPreferences(file_name, Context.MODE_PRIVATE);
        } else {
            sp = context.getSharedPreferences(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }


    /**
     * 查询某个key是否已经存在
     *
     * @param context
     * @param key
     * @return
     */
    public static boolean contains(Context context, String file_name, String key) {
        SharedPreferences sp;
        if (file_name != null) {
            sp = context.getSharedPreferences(file_name, Context.MODE_PRIVATE);
        } else {
            sp = context.getSharedPreferences(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
        }
        return sp.contains(key);
    }


    /**
     * 返回所有的键值对
     *
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context, String file_name) {
        SharedPreferences sp;
        if (file_name != null) {
            sp = context.getSharedPreferences(file_name, Context.MODE_PRIVATE);
        } else {
            sp = context.getSharedPreferences(DEFAULT_FILE_NAME, Context.MODE_PRIVATE);
        }
        return sp.getAll();
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     *
     * @author zhy
     */
    public static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {

            }
            return null;
        }

        /**
         * 如果找到则使用apply执行，否则使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {

            } catch (IllegalAccessException e) {

            } catch (InvocationTargetException e) {

            }
            editor.commit();
        }
    }
}